// app/login/page.tsx
'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { authService } from '@/services/api/auth'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'

export default function LoginPage() {
  const router = useRouter()
  const [formData, setFormData] = useState({
    username: '',
    password: '',
  })

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    try {
      await authService.login(formData)
      // 获取重定向地址
      const searchParams = new URLSearchParams(window.location.search)
      const from = searchParams.get('from') || '/'
      router.push(from)
    } catch (error) {
      // 错误已在请求拦截器中处理
      console.error(error)
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center">
      <form onSubmit={handleSubmit} className="space-y-4 w-full max-w-md p-8">
        <h1 className="text-2xl font-bold text-center">登录</h1>
        <div className="space-y-2">
          <Input
            type="text"
            placeholder="邮箱"
            value={formData.username}
            onChange={(e) =>
              setFormData((prev) => ({ ...prev, username: e.target.value }))
            }
          />
          <Input
            type="password"
            placeholder="密码"
            value={formData.password}
            onChange={(e) =>
              setFormData((prev) => ({ ...prev, password: e.target.value }))
            }
          />
        </div>
        <Button type="submit" className="w-full">
          登录
        </Button>
      </form>
    </div>
  )
}
